package com.cmwa.scbp.utils.cached;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cmwa.scbp.base.constants.Constant;
import com.cmwa.scbp.base.mvc.entity.SearchParam;
import com.cmwa.scbp.base.exception.CachedException;
import com.cmwa.scbp.sys.msg.service.IMsgConfService;
import com.cmwa.scbp.sys.msg.vo.MsgConfVo;
import com.cmwa.scbp.utils.cached.service.ShareCachedService;
import com.cmwa.scbp.utils.spring.SpringContextUtil;

/**
 * 消息配置-待办缓存类
 * 
 * @author zhangys
 */
public class MsgBacklogCached  implements ShareCachedService {

	private static Logger logger = LoggerFactory.getLogger(MsgBacklogCached.class);
	
	@Resource
	private IMsgConfService msgConfService;
	
	public static Map<String, MsgConfVo> dictCached = new HashMap<String, MsgConfVo>();//待办对应的数量
	
	public static List<MsgConfVo> msgConfVoEmpRs = new ArrayList<MsgConfVo>();//待办对应的收件人

	/**
	 * 项目启动时查出scbp首页待办缓存
	 */
	@Override
	public void loadMappingCached() throws CachedException {
		try {
			dictCached.clear();
			msgConfVoEmpRs.clear();
			//查出所有待办，并设置相应的数量
			SearchParam sp = new SearchParam();
			sp.getSp().put("sendType", "Backlog");
			sp.getSp().put("runStatus", "R");
			List<MsgConfVo> msgConfVos = msgConfService.msgConfList(sp);
			for(int i=0;i<msgConfVos.size();i++){
				getBacklog(msgConfVos.get(i));//查询待办的数量，并放入缓存里

				msgConfVoEmpRs.add(msgConfVos.get(i));//查询待办对应的收件人，并放入缓存里
			}
		} catch (Exception e) {
			logger.error("消息配置待办加载异常：", e);
			e.getStackTrace();
		}
	
	}

	/**
	 * 查询待办的数量，并放入缓存里
	 * @param url (待办路径)
	 * @param json (参数,json字符串格式)
	 * @return
	 */
	public static void getBacklog(MsgConfVo vo){
		
		try {
			String url=vo.getBacklogUrl();//待办路径
			String parameter=vo.getBacklogParameter();//参数
			int inex=url.lastIndexOf(".");
			String classUrl = url.substring(0,inex);//类路径
			String methodName = url.substring(inex+1,url.length());//方法名
			
		    Class<?> t = Class.forName(classUrl);
		    Object obj = SpringContextUtil.getBean(t);
		    Method method = t.getMethod(methodName, String.class);
            String result=(String)method.invoke(obj, parameter);
            vo.setBacklogOrMonitors(result);
		} catch (Exception e) {
			vo.setBacklogOrMonitors(Constant.CONSTANT_STRING_ZERO);
			logger.error("消息配置待办通过反射调用方法查询数量出现异常,待办路径:"+vo.getBacklogUrl()+",参数:"+vo.getBacklogParameter(), e);
			//e.printStackTrace();
		}
		dictCached.put(vo.getId(), vo);
	}
}
